package com.gzedu.ecloud.common.utils;

import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

public abstract class Lang {
	/**
	 * 判断一个对象是否为空。它支持如下对象类型：
	 * <ul>
	 * <li>null : 一定为空
	 * <li>数组
	 * <li>集合
	 * <li>Map
	 * <li>其他对象 : 一定不为空
	 * </ul>
	 * 
	 * @param obj
	 *            任意对象
	 * @return 是否为空
	 */
	public static boolean isEmpty(Object obj) {
		if (obj == null)
			return true;
		if (obj.getClass().isArray())
			return Array.getLength(obj) == 0;
		if (obj instanceof Collection<?>)
			return ((Collection<?>) obj).isEmpty();
		if (obj instanceof Map<?, ?>)
			return ((Map<?, ?>) obj).isEmpty();
		return false;
	}

	/**
	 * 判断一个数组是否是空数组
	 * 
	 * @param ary
	 *            数组
	 * @return null 或者空数组都为 true 否则为 false
	 */
	public static <T> boolean isEmptyArray(T[] ary) {
		return null == ary || ary.length == 0;
	}

	/**
	 * 将一个数组转换成字符串
	 * <p>
	 * 每个元素之间，都会用一个给定的字符分隔
	 * 
	 * @param c
	 *            分隔符
	 * @param objs
	 *            数组
	 * @return 拼合后的字符串
	 */
	public static <T> StringBuilder concat(Object c, T[] objs) {
		StringBuilder sb = new StringBuilder();
		if (null == objs || 0 == objs.length)
			return sb;

		sb.append(objs[0]);
		for (int i = 1; i < objs.length; i++)
			sb.append(c).append(objs[i]);

		return sb;
	}

	/**
	 * 根据格式化字符串，生成运行时异常
	 * 
	 * @param format
	 *            格式
	 * @param args
	 *            参数
	 * @return 运行时异常
	 */
	public static RuntimeException makeThrow(String format, Object... args) {
		return new RuntimeException(String.format(format, args));
	}

	/**
	 * 生成UUID
	 * 
	 * @return
	 */
	public static String makeUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String byteToHexString(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString.append(hex);
		}
		return hexString.toString();
	}

	public static MessageDigest getDigest(String algorithmName) throws NoSuchAlgorithmException {
		return MessageDigest.getInstance(algorithmName);
	}

	public static String md5(byte[] bytes, byte[] salt, int hashIterations) throws NoSuchAlgorithmException {
		MessageDigest digest = getDigest("md5");
		if (salt != null) {
			digest.reset();
			digest.update(salt);
		}
		byte[] hashed = digest.digest(bytes);
		int iterations = hashIterations - 1;

		for (int i = 0; i < iterations; ++i) {
			digest.reset();
			hashed = digest.digest(hashed);
		}
		return Hex.encodeHexString(hashed);
	}
}
